<?php

namespace app\site\controller\site;

use app\common\exception\MiException;
use app\site\controller\AController;
use app\site\controller\traits\CurdTrait;
use app\site\service\site\DiyPageService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Config;
use think\Request;
use think\response\Json;

class DiyPageController extends AController
{

    /**
     * @throws MiException
     */
    public function add(){
        return $this->reqSer->setService(DiyPageService::instance())->add()->getResponse();
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function edit(\app\Request $request){
        if($request->isPost()){
            return $this->reqSer->setService(DiyPageService::instance())->edit()->getResponse();
        }else{
            return $this->reqSer->setService(DiyPageService::instance())->setFind()->getResponse();
        }
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function del(){
        return $this->reqSer->setService(DiyPageService::instance())->delete()->getResponse();
    }

    /** 首页模板列表
     * @throws DbException
     */
    public function index(){
        return $this->reqSer->setService(DiyPageService::instance()->setWhere(['page_type' => 'index']))->setPaginate()->getResponse();
    }

    /**
     * 所有页面的跳转路径
     * @param Request $request
     * @return Json
     */
    public function getUrls(Request $request): Json
    {
        $urls = Config::get('page_url');

        return jsonSuccess([
            'urls' => $urls
        ]);
    }


    /**
     * 商品分类页编辑
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function goodsCateEdit(Request $request): Json
    {
        if($request->isPost()){

            $post = $this->post();
            if ($post['id']??''){
                $info =DiyPageService::instance()->update($post, ['id'=>$post['id']]);
            }else{
                $info = DiyPageService::instance()->create($post);
            }

        }else{

            $info = DiyPageService::instance()->setWhere([
                ['page_type', '=', 'goods_cate']
            ])->find();

        }
        return jsonSuccess([
            'info' => $info,
        ]);
    }

}
